/**
	首页
 */
Ext.define('ShineECallView.view.template.ElementGrid', {
    extend: 'Ext.grid.Panel',
    xtype:"templateelementgrid",
    layout:"fit",
    title:"模板素材",
    currentElementId:0,
    emptyText:"暂无数据！",
    viewModel:{
        data:{
            selectedRds:0
        }
    },
    plugins: {
        rowediting: {
            clicksToEdit: 2,
            saveBtnText:"保存",
            cancelBtnText:"取消"
        }
    },
	constructor:function(config){
		this.superclass.constructor.call(this, config);
	},
    initComponent: function() {
        var me = this;
        me.applyElementGrid();
		me.callParent();
    },
    listeners:{
        itemclick:function (cmp, record, item, index, e, eOpts ){
            this.currentElementId = record['data']['element_id'];
            ShineMessageHub.fireEvent("templateelementgriditemclickevent",record);
        },
        selectionchange:function(c, selected, eOpts){
            var me = this;
            me.getViewModel().setData({
                selectedRds:selected
            });
        },
        edit:function(editor, e){
            var me = this;
            // commit the changes right after editing finished
            Ext.Ajax.request({
                method:"PUT",
                params:e.record['data'],
                url: SHINEECALLHOST+"/tpl.php/records/shine_template_element/"+e.record['data']['element_id'],
                success: function(response, opts) {
                    var rspObj = Ext.decode(response.responseText);
                    e.record.commit();
                    console.log(rspObj);
                    me.store.reload();
                },
           
                failure: function(response, opts) {
                    console.log(response);
                    console.log('server-side failure with status code ' + response.status);
                }
            });
            
        }
    },

    /***
     * 初始化函数
     * *****/
    applyElementGrid:function(){
        var me = this;

        var store = Ext.create('Ext.data.Store', {
            fields:[
                "element_description",
                "element_id",
                "element_name",
                "element_path",
                "element_type_id"
            ],
            pageSize: 100,
            remoteSort: true,
            autoLoad:true,
            sorters: [{
				property: 'element_name',
				direction: 'ASC'
			}],
            proxy: {
                type: 'ajax',
                method:"GET",
                url: SHINEECALLHOST+"/tpl.php/records/shine_template_element",
                reader: {
                    type: 'json',
                    rootProperty: 'records',
                    totalProperty: 'results'
                }
            },
            listeners:{
                beforeload:function(store, operation, eOpts){
                    var _direction = operation['_sorters'][0]['_direction'];
                    var _property = operation['_sorters'][0]['_property'];
                    operation['_params'] = {order:_property+","+_direction};//排序操作
                },
                load:function( c, records, successful, operation, eOpts){
                    var lastEditRd = null;
                    Ext.each(records,function(itemRd){
                        if(itemRd['data']['element_id'] == me.currentElementId){
                            lastEditRd = itemRd;
                        }
                    });
                    if(lastEditRd!=null){
                        me.getSelectionModel().select([lastEditRd]);//选中上次编辑的记录
                        me.getView().focusRow(lastEditRd);//锁定上次编辑的记录
                    }

                }
            }
        });

        Ext.apply(me,{
            store:store,
            bbar:[{
                xtype: 'pagingtoolbar',
                store:store,
                displayInfo: true
            }],
            tbar:[{
                text:"上传",
                icon:"resources/shine/images/icon2/add.png",
                handler:function(){
                    var win = Ext.create("Ext.window.Window",{
                        title:"上传图片",
                        closeAction:"close",
                        modal:true,
                        width:700,
                        height:400,
                        autoScroll:true,
                        html:'<iframe style="width:100%;height:99%;border:0px;" src="'+SHINEECALLHOST +'/interface/html5upload/index.html?type='+me.backgroundImageType+'"></iframe>',
                        buttons:[{
                            text:"关闭",
                            handler:function(){
                                win.close();
                                me.store.reload();
                            }
                        }]
                    });

                    win.show();
                }
            },'-',{
                text:"删除",
                disabled:true,
                bind:{
                    disabled:"{selectedRds.length==0}"
                },
                icon:"resources/shine/images/icon2/delete.png",
                handler:function(){
                    Ext.Msg.show({
                        title:"操作提示",
                        msg:"是否要删除选中的素材？",
                        width:300,
                        icon:Ext.Msg.QUESTION,
                        buttons:Ext.Msg.YESNO,
                        fn:function(idx){
                            if("yes" == idx){
                                me.deleteElement();
                            }
                        }
                    });
                }
            },'->',{
                text:"刷新",
                icon:"resources/shine/images/icon2/refresh.png",
                handler:function(){
                    me.store.reload();
                }
            }],
            columns: [
                {
                    width:50,
                    align:'center',
                    xtype: 'rownumberer',
                    text:"行号"
                },
                { text: '素材名称', dataIndex: 'element_name',width:300,
                    editor:{
                        xtype:"textfield",
                        allowBlank:false
                    }
                },
                { text: '素材路径', dataIndex: 'element_path',flex:1 }
            ]
        });
    },

    /********
     * 
     * 删除素材
     * 
     * *********/
    deleteElement:function(){
        var me = this;
        var rds = me.getSelectionModel().getSelection();
        var ids = [];
        Ext.each(rds,function(item){
            ids.push(item['data']['element_id']);
        });

        Ext.Msg.wait("删除中，请稍后... ...","操作提示");

        Ext.Ajax.request({
            method:"POST",
            params:{ids:Ext.encode(ids)},
            url: SHINEECALLHOST+"/admin/template/template/deleteimg",
            success: function(response, opts) {
                var rspObj = Ext.decode(response.responseText);
                Ext.Msg.show({
                    title:"操作提示",
                    msg:"删除成功！",
                    width:300,
                    icon:Ext.Msg.INFO,
                    buttons:Ext.Msg.OK,
                    fn:function(idx){
                        me.store.reload();
                    }
                });
                
            },
       
            failure: function(response, opts) {
                console.log(response);
                console.log('server-side failure with status code ' + response.status);
            }
        });

    },

    selModel: {
        selType: 'checkboxmodel',
        mode   : 'MULTI'
    }
});
